
/*
  needs libmosquitto-dev
  $ gcc -o libmosq libmosq.c -lmosquitto
*/
#include <stdio.h>
#include <mosquitto.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct mosquitto *mosq = NULL;
char const *topic = NULL;

void mosq_log_callback(struct mosquitto *mosq, void *userdata, int level, const char *str)
{
	/* Pring all log messages regardless of level. */
  
  switch(level){
    //case MOSQ_LOG_DEBUG:
    //case MOSQ_LOG_INFO:
    //case MOSQ_LOG_NOTICE:
    case MOSQ_LOG_WARNING:
    case MOSQ_LOG_ERR: {
      printf("%i:%s\n", level, str);
    }
  }
  
	
}
void (*g_mosq_msg_handler)(char const *topic, char const *payload, int payload_len);
void mosq_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg) {
	g_mosq_msg_handler(msg->topic, (char const *)msg->payload, msg->payloadlen);
}
void mosq_disconn_callback(struct mosquitto *mosq, void *userdata, int reason) {
        mosquitto_reconnect(mosq);
}
void mosq_conn_callback(struct mosquitto *mosq, void *userdata, int reason) {
	mosquitto_subscribe(mosq, NULL, topic, 0);
}



void mqtt_setup(char const *ip, int pport, char const *subtopicpattern, void (*hdr)(char const *, char const *, int)){

	char const *host = ip;//"localhost";
	int port = pport;//1883;
	int keepalive = 60;
	bool clean_session = true;
  topic = subtopicpattern;//"/testtopic";
  
  mosquitto_lib_init();
  mosq = mosquitto_new(NULL, clean_session, NULL);
  if(!mosq){
		fprintf(stderr, "Error: Out of memory.\n");
		exit(1);
	}
  
  mosquitto_log_callback_set(mosq, mosq_log_callback);
  mosquitto_disconnect_callback_set(mosq, mosq_disconn_callback); 
  mosquitto_connect_callback_set(mosq, mosq_conn_callback);
  g_mosq_msg_handler = hdr;
  mosquitto_message_callback_set(mosq, mosq_message_callback);
  if(mosquitto_connect(mosq, host, port, keepalive)){
		fprintf(stderr, "<Unable to connect.>\n");
//		exit(1);
	}
  int loop = mosquitto_loop_start(mosq);
  if(loop != MOSQ_ERR_SUCCESS){
    fprintf(stderr, "Unable to start loop: %i\n", loop);
    exit(1);
  }
}

int mqtt_send(char const *ptopic, char *msg, int len){
  return mosquitto_publish(mosq, NULL, ptopic, len, msg, 0, 0);
}
